<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;

class GamesController extends Controller
{
    //add
    public function add()
	{
	    //选择出id name path 字段,并且数据按照path排序
		$data = DB::table('games') -> select('id','name','path',DB::raw("concat(path,',',id) AS sort_str")) -> orderBy('sort_str') -> get();
	
	    //遍历获取path(给path分层)
	    foreach($data as $key => $value)
	    {
	        $num = substr_count($value -> path ,',');
	        $str = str_repeat('|----',$num);
	        $data[$key] -> name = $str.$value -> name;
	    }
		return view('admin.games.add',['data' => $data]);

	}
	//insert
	public function insert(Request $request)
	{
        //判断数据是否合法
        $this -> validate($request,[
            'file' => 'file',
            'logo' => 'image',
            'name' => 'required',
            ],[
            'file.file' => '请选择合法文件',
            'logo.image' => '请选择合法图片',
            'name.required' => '游戏名不能为空',
            ]);

		$data = $request -> except('_token');

        //处理图片
        if($request -> hasFile('logo'))
        {
            //获取扩展名
            if($request -> file('logo') -> isValid())
            {
                $extension = $request -> file('logo') -> getClientOriginalExtension();
                $fileName = str_random(32).'.'.$extension;
                $d = date('Ymd');
                $dir = './uploads/games/imgs/'.$d;

                if(!file_exists($dir))
                {
                    mkdir($dir,0777,true);

                }
                //移动文件
                $move = $request -> file('logo') -> move($dir,$fileName);

                if($move)
                {
                    $data['logo'] = $fileName;
                   
                }
            }
        }

        //处理文件
        if($request -> hasFile('file'))
        {
            //获取扩展名
            if($request -> file('file') -> isValid())
            {
                $extension = $request -> file('file') -> getClientOriginalExtension();
                $fileName = str_random(32).'.'.$extension;
                $d = date('Ymd');
                $dir = './uploads/games/files/'.$d;

                if(!file_exists($dir))
                {
                    mkdir($dir,0777,true);

                }
                //移动文件
                $move = $request -> file('file') -> move($dir,$fileName);

                if($move)
                {
                    $data['file'] = $fileName;
                  
                }
            }
        }
        
        
		if($data['pid'] == 0)
        {
            $path = '0';

        }else
        {
            //获取数据表中id= pid的数据
            $pdata = DB::table('games') -> where('id',$data['pid']) -> first();
            //拼装新的路径
            $path = $pdata -> path.','.$data['pid'];
          
        }
            $data['time'] = time();
            $data['path'] = $path;

            //将数据插入数据库
            $res = DB::table('games') -> insert($data);

            if($res)
            {
                return redirect('/admin/games/index') -> with(['info' => '添加成功']);

            }else
            {
                return back() -> with(['info' => '添加失败']);
            }
	}

	//index
	public function index()
	{
		//选择出id name path 字段,并且数据按照path排序
        $data = DB::table('games') -> select('id','name','path',DB::raw("concat(path,',',id) AS sort_str")) -> orderBy('sort_str') -> get();
        
        //遍历获取path(给path分层)
        foreach($data as $key => $value)
        {
            
            $num = substr_count($value -> path ,',');
            $str = str_repeat('|----',$num);
            $data[$key] -> name = $str.$value -> name;
        }
        return view('admin.games.index',['data' => $data]);
	}

	public function edit($id)
	{
		
		$allData = DB::table('games') -> select('id','name','path',DB::raw("concat('path,',',id') AS sort_str")) -> orderBy('sort_str') -> get();

        foreach($allData as $key => $value)
        {
            $num = substr_count($value -> path,',');
            $str = str_repeat('|----',$num);
            $allData[$key] -> name = $str.$value -> name;
        }

        $data = DB::table('games') -> where('id',$id) -> first();
        $time = $data -> time;
        $time = date('Ymd',$time);
        return view('admin.games.edit',['data' => $data,'allData' => $allData,'time' => $time]);
	}

	//update 
    public function update(Request $request,$id)
    {
        $data = $request -> except('_token');
        if($data['pid'] == 0)
        {
            $path = '0';

        }else
        {
            //获取数据库中id = pid数据
            $pdata = DB::table('games') -> where('id',$data['pid']) -> first(); 

            //拼装新的路径                   
            $path = $pdata -> path .','.$data['pid'];
        }
        $data['path'] = $path;

        //执行修改
        $res = DB::table('games') -> where('id',$id) -> update($data);

        if($res)
        {
            return redirect('/admin/games/index') -> with(['info' => '编辑成功']);
        }else
        {
            return back() -> with(['info' => '编辑失败']);
        }
    }

    //delete删除
    public function delete($id)
    {

        //查询是否有子分类
        $res = DB::table('games') -> where('pid',$id) -> first();
        
        if($res)
        {
            return back() -> with(['info' => '无法删除(有子分类)']);
        }

        //获取原logo及文件路径
        $oldLogo = DB::table('games') -> where('id',$id) -> first() -> logo;
        $tLogo = DB::table('games') -> where('id',$id) -> first() -> time;
        $oldFile = DB::table('games') -> where('id',$id) -> first() -> file;
        $tLogo = date('Ymd',$tLogo);
        $logoPath = './uploads/games/imgs/'.$tLogo.'/'.$oldLogo;
        $filePath = './uploads/games/files/'.$tLogo.'/'.$oldFile;
      
        //执行删除
        $res = DB::table('games') -> delete($id);

       
        if($res)
        {
            //执行游戏文件及logo删除
            
            if(file_exists($logoPath))
            {
                unlink($logoPath);
            }
            if(file_exists($filePath))
            {
                unlink($filePath);
            }

            return redirect('/admin/games/index') -> with(['info' => '删除成功']);
        }else
        {
            return back() -> with(['info' => '删除失败']);
        }

    }
}

